package com.ylbh.modules.businesscoupon.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylbh.common.pojo.businesscoupon.dto.StoreCouponDTO;
import com.ylbh.common.pojo.member.vo.MemberVO;
import com.ylbh.common.utils.IdWorker;
import com.ylbh.common.utils.ShiroUtils;
import com.ylbh.modules.businesscoupon.entity.ShoppingStoreCoupon;
import com.ylbh.modules.businesscoupon.mapper.ShoppingStoreCouponMapper;
import com.ylbh.modules.businesscoupon.service.ShoppingStoreCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylbh.common.utils.PageUtils;


@Service("shoppingStoreCouponService")
public class ShoppingStoreCouponServiceImpl extends ServiceImpl<ShoppingStoreCouponMapper, ShoppingStoreCoupon> implements ShoppingStoreCouponService {

    @Autowired
    private ShoppingStoreCouponMapper shoppingStoreCouponMapper;

    /**
     * 商家优惠券列表
     * @param storeCouponDTO
     * @return
     */
    @Override
    public PageUtils queryStoreCouponList(StoreCouponDTO storeCouponDTO) {
        Page page = new Page(storeCouponDTO.getPage(), storeCouponDTO.getLimit());
        List<ShoppingStoreCoupon> list = shoppingStoreCouponMapper.selectStoreCouponList(storeCouponDTO, page);
        return new PageUtils(new Page<ShoppingStoreCoupon>().setRecords(list).setTotal(page.getTotal()));
    }

    /**
     * 查看商家优惠券详情
     * @param id
     * @return
     */
    @Override
    public ShoppingStoreCoupon getStoreCouponInfoById(String id) {
        return shoppingStoreCouponMapper.selectStoreCouponInfoById(id);
    }

    /**
     * 优惠券审核操作
     * @param shoppingStoreCoupon
     */
    @Override
    public void toExamineCouponById(ShoppingStoreCoupon shoppingStoreCoupon) {
        // 修改商家优惠券的审核状态
        shoppingStoreCouponMapper.updateStoreCouponStatusById(shoppingStoreCoupon.getId(), shoppingStoreCoupon.getCheck(), shoppingStoreCoupon.getCheckNoPass());
        if (shoppingStoreCoupon.getCheck() == 0) {
            // 审核不通过

            // 查询用户现在金额
            BigDecimal recommendMoney = shoppingStoreCouponMapper.selectRecommendMoneyByUserId(shoppingStoreCoupon.getId());

            // 则要将商家支付的金额退还到账户
            shoppingStoreCouponMapper.updateRecommendMoneyById(shoppingStoreCoupon.getId(), recommendMoney);

            // 先查询用户信息
            MemberVO vo = shoppingStoreCouponMapper.selectUserDetailsById(shoppingStoreCoupon.getId());
            // 增加日志信息
            shoppingStoreCouponMapper.insertBalanceLog(vo, new Date(), ShiroUtils.getUserId(), new IdWorker().nextId(), shoppingStoreCoupon.getId());
        }
    }
}
